﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;

namespace Web.Ajax.Data.HttpDatabase
{
	public class RequestMethod
	{
		public const string PUT = "put";
		public const string POST = "post";
		public const string GET = "get";
		public const string DELETE = "delete";

		public HttpContext HttpContext;
		public HttpRequest Request;
		public HttpResponse Response;

		public Path Path;
		public ContentType ContentType;
		public bool EnsureCollection = false;
		public Collection Collection;

		public static RequestMethod Create(HttpContext c)
		{
			RequestMethod rm=null;
			var m = c.Request.RequestType.ToLower();
			switch (m)
			{
				case GET:
					rm= new Get();
					break;
				case PUT:
				case POST:
					rm= new Save();
					break;
				case DELETE:
					rm= new Delete();
					break;
			}
			if (rm == null)
			{
				StatusCode.Set(StatusCode.MethodNotAllowed, c);
				return null;
			}
			else
			{
				rm.HttpContext = c;
				rm.Request = c.Request;
				rm.Response = c.Response;
				var p = c.Request.Path;
				if (p.StartsWith(c.Request.ApplicationPath))
					p = p.Substring(c.Request.ApplicationPath.Length + 1);
				rm.ContentType = ContentType.GetByHttpValue(c.Request.ContentType);
				var path = new Path(p);
				path.AnalyzePath(rm.ContentType,rm.EnsureCollection);
				rm.Path = path;
				if (path.IsCollection)
					rm.Collection = new Collection(path.CollectionPhysicalPath);
				return rm;
			}
		}

		public virtual void ProcessRequest()
		{
			Authorize();
			ProcessMethod();
		}

		public virtual void Authorize()
		{

		}

		public virtual void ProcessMethod()
		{

		}

		private string RequestData;
		private bool getRequestDataCalled;
		public string GetRequestData()
		{
			if (!getRequestDataCalled)
			{
				int length = (int)Request.InputStream.Length;
				byte[] bytes = new byte[length];
				Request.InputStream.Read(bytes, 0, length);
				RequestData = Encoding.UTF8.GetString(bytes);
			}
			return RequestData;
		}
		public object GetRequestObject()
		{
			var json = GetRequestData();
			return (Hashtable)Json.ConvertFromJson(typeof(Hashtable), json);
		}
	}
}
